﻿@{
    Layout = null;
    //EntityId(必需参数)--实体id
    //EntityName(必需参数)--
    //RelevantEntityId（可选参数）--相关实体id
    //

    //保存
    //eachGroup(e, isFirst); --e代表需要保存的筛选列表，可以是主实体的筛选列表，也可以是相关实体的筛选列表，isFirst 是否第一层 。 保存到QueryObject.Criteria
    //eachRelevant(e, entityrelationship)  --保存实体的相关实体，保存到QueryObject.LinkEntities
    //上面两个保存可参考reportviewer.aspx 里面的js saveFilter()

    //编辑
    //initFilter(entityFilter, $('#pliot-page1').find('div[data-type="Main"]'));--传入实体数据
    //initFilter(relatedEntityFilter, $('#pliot-page1').find('div[data-type="Relevant"]'));传入相关实体数据
}

<div class="modal-body" id="pliot-page1" data-page="1">
    <div class="form-group">
        <label for="pilot-newreport">主要记录筛选条件</label>
    </div>
    <div class="form-group">
        <div class="btn-group btn-group-sm">
            <button type="button" onclick="clearRowGroup(this)" class="btn btn-default">清除</button>
            <button type="button" onclick="groupAndOr(this,'and')" class="btn btn-default">组“和”</button>
            <button type="button" onclick="groupAndOr(this,'or')" class="btn btn-default">组“或”</button>
        </div>
    </div>
    <div class="form-group" data-type="Main">
        <div id="row_1" class="pilot-row row" data-isshow="show" style="margin-bottom:5px;">
            <div class="col-sm-1" style="position:relative;height:30px;">
                <em class="pilot-choose" onclick="downSelect(this,'row')" style="display: none; background: url(/content/images/selectListR.png) center no-repeat; position: absolute; height: 15px; width: 15px; top: 30%; left: 50%; cursor: pointer;"></em>
            </div>
            <div class="col-sm-11">
                <select class="form-control pilot-fieldM pilot-null input-sm">
                    <option value="">--请选择--</option>
                </select>
            </div>
            <div class="col-sm-3 hide">
                <select class="form-control pilot-condition input-sm">
                    <option>--请选择--</option>
                </select>
            </div>
            <div class="col-sm-4 hide">
                <input class="form-control input-sm" name="value" type="text" value="" />
            </div>
            <br />
        </div>
        <div class="clearfix"></div>
    </div>
    <div class="form-group">
        <label for="pilot-oldreport">相关记录筛选条件</label>
    </div>
    <div class="form-group">
        <div class="btn-group btn-group-sm">
            <button type="button" onclick="clearRowGroup(this)" class="btn btn-default">清除</button>
            <button type="button" onclick="groupAndOr(this,'and')" class="btn btn-default">组“和”</button>
            <button type="button" onclick="groupAndOr(this,'or')" class="btn btn-default">组“或”</button>
        </div>
    </div>
    <div class="form-group" data-type="Relevant">
        <div id="row_2" class=" pilot-row row" data-isshow="show" style="margin-bottom:5px;">
            <div class="col-sm-1" style="position:relative;height:30px;">
                <em class="pilot-choose" onclick="downSelect(this,'row')" style="display: none; background: url(/content/images/selectListR.png) center no-repeat; position: absolute; height: 15px; width: 15px; top: 30%; left: 50%; cursor: pointer;"></em>
            </div>
            <div class="col-sm-11">
                <select class="form-control pilot-fieldR pilot-null input-sm">
                    <option value="">--请选择--</option>
                </select>
            </div>
            <div class="col-sm-3 hide">
                <select class="form-control pilot-condition input-sm">
                    <option>--请选择--</option>
                </select>
            </div>
            <div class="col-sm-4 hide">
                <input class="form-control input-sm" name="value" type="text" value="" />
            </div>
        </div>
        <div class="clearfix"></div>
    </div>
    <div class="clearfix"></div>
</div>

<script>
    $(function () {
        $('body').off('change', '.pilot-null');
        $('body').on('change', '.pilot-null', function () {
            if ($(this).find('option:selected').val() != '' && $(this).find('option:selected').attr('data-relevant') == 'false') {
                if ($(this).parents('.pilot-row:eq(0)').attr('data-relevant') == 'true') {
                    var parRentityid = $(this).parents('.relevant-box:eq(0)').attr('data-rentityid');
                    var newSelect = CopyNewRow($(this).parents('.form-group').find('.pilot-row:last'), 'false', 'true', parRentityid);
                    $(this).parents('.pilot-row:eq(0)').after(newSelect);
                } else {
                    var newSelect = CopyNewRow($(this).parents('.pilot-row:eq(0)'), 'false', 'false', '');
                    $(this).parents('.pilot-row:eq(0)').after(newSelect);
                }
            } else if ($(this).parents('.pilot-row:eq(0)').parent().hasClass('relevant-child') == false) {
                var newSelect = CopyNewRow($(this).parents('.pilot-row:eq(0)'), 'false', 'false', '');
                $(this).parents('.pilot-row:eq(0)').after(newSelect);
            }
        });
        $('body').off('change', '.pilot-fieldM,.pilot-fieldR');
        $('body').on('change', '.pilot-fieldM,.pilot-fieldR', function () {
            var datatype = $(this).find('option:selected').attr('data-type');
            var dataname = $(this).find('option:selected').val();
            var dataentityname = $(this).find('option:selected').attr('data-entityname');
            var isrelevant = $(this).find('option:selected').attr('data-relevant');
            var attributeid = $(this).find('option:selected').attr('data-attributeid');
            var optionsetid = $(this).find('option:selected').attr('data-optionsetid');
            var relevantEntityId = $(this).find('option:selected').attr('data-referencedentityid');
            var referencedentityname = $(this).find('option:selected').attr('data-referencedentityname');
            console.log(isrelevant)
            var ddlitems = getDdlItems(datatype);
            if (isrelevant == 'true') {
                var selRela = $(this).find('option:selected').attr('data-name');
                var checkList = $(this).parent().parent('.pilot-row').siblings('.relevant-box');
                var isIn = false;
                var thatSel = $(this);
                checkList.each(function (i, n) {
                    var sibEntityid = $(n).attr('data-rrelationship');
                    if (selRela.toLowerCase() == sibEntityid.toLowerCase()) {
                        if (thatSel.find('option[value=""]').length > 0) {
                            thatSel.find('option[value=""]').prop('selected', true);
                        } else {
                            var thatEntityid = thatSel.parent().parent().attr('data-rentityid');
                            thatSel.find('option[data-entityid="' + thatEntityid + '"]').prop('selected', true);
                        }
                        isIn = true;
                        Xms.Web.Alert(false, '查询已存在所要添加的条件');
                        return false;
                    }
                });
                if (isIn == true) {
                    return false;
                }
            }
            if ($(this).find('option:selected').val() == '') {
                $(this).parent().addClass('col-sm-11').removeClass('col-sm-4');
                $(this).parent().nextAll().addClass('hide');
                $(this).parents('.pilot-row:eq(0)').find('.pilot-choose').hide();
                return false;
            }
            else {
                $(this).removeClass('pilot-null');
                $(this).parent().removeClass('col-sm-11').addClass('col-sm-4');
                $(this).parent().nextAll().removeClass('hide');
                $(this).parents('.pilot-row:eq(0)').find('.pilot-choose').show();
            }
            if (isrelevant == 'false') {
                $(this).parents('.pilot-row:first').attr('data-type', datatype);
                $(this).parents('.pilot-row:first').attr('data-attributename', dataname);
                $(this).parents('.pilot-row:first').attr('data-entityname', dataentityname);
                $(this).parents('.pilot-row:first').attr('data-attributeid', attributeid);
                $(this).parents('.pilot-row:first').attr('data-optionsetid', optionsetid);

                datatype = datatype == "primarykey" ? 'lookup' : datatype ? datatype : "nvarchar";

                var operators = Xms.Fetch.ConditionOperators[datatype];
                if (datatype == 'status') {
                    operators = Xms.Fetch.ConditionOperators['picklist'];
                }
               // console.log('referencedentityname', referencedentityname && referencedentityname != 'undefined')
                if (referencedentityname && referencedentityname != 'undefined') {
                    //console.log(datatype == "lookup" || datatype == "owner" || datatype == "customer")
                    if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {

                       // console.log('ConditionOperator', Xms.Fetch.ConditionOperator)
                        if (referencedentityname.toLowerCase() == "systemuser") {
                            operators = Xms.Fetch.ConditionOperator.SystemUserOperators;
                        } else if (referencedentityname.toLowerCase() == "businessunit") {
                            operators = Xms.Fetch.ConditionOperator.BusinessUnitOperators;
                        } else if (referencedentityname.toLowerCase() == "organization") {
                            operators = Xms.Fetch.ConditionOperator.OrganizationOperators;
                        }
                    }
                }
                console.log('operators', operators)
                //操作符
                var op = new Array();
                $(operators).each(function (i, n) {
                    op.push('<option data-value="' + n[0] + '" value="' + n[1] + '">' + n[2] + '</option>');
                });
                $(this).parents('.pilot-row:first').find('.pilot-condition').html(op.join(''));
                $(this).parents('.pilot-row:first').find('.pilot-condition').change();
                if ($(this).hasClass('pilot-fieldM')) {
                    if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                        FilterDialog.bindInput($(this).parents('.pilot-row:eq(0)').find('.pilot-condition'), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, attributeid, relevantEntityId, ddlitems, optionsetid);
                    } else {
                        FilterDialog.bindInput($(this).parents('.pilot-row:eq(0)').find('.pilot-condition'), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, attributeid, EntityId, ddlitems, optionsetid);
                    }
                }
                else if ($(this).hasClass('pilot-fieldR')) {
                    FilterDialog.bindInput($(this).parents('.pilot-row:eq(0)').find('.pilot-condition'), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, attributeid, relevantEntityId, ddlitems, optionsetid);
                }
            }
            else {//如果是关联表
                var that = $(this);
                if ($(this).parent().hasClass('relevant-item')) {
                    Xms.Web.Confirm(false, '所有字段及该实体的相关实体将会清除，是否继续？', function () {
                        that.siblings().remove();
                        relevantEvent(that, dataentityname);
                    }, function () {
                        that.find('option[value="' + that.parent().attr('data-name') + '"]').prop('selected', true);
                        return false;
                    });
                } else {

                    relevantEvent(that, dataentityname);
                }
            }
        });
        $('body').off('change', '.pilot-condition');
        $('body').on('change', '.pilot-condition', function () {
            var datatype = $(this).parents('.pilot-row:eq(0)').attr('data-type');
            var ddlitems = getDdlItems(datatype);
            var relevantEntityId = $(this).parents('.pilot-row:first').find('select.pilot-fieldM option:selected').attr('data-referencedentityid');
            //console.log(relevantEntityId)
            var dataoperator = $(this).find('option:selected').val();
            $(this).parents('.pilot-row:eq(0)').attr('data-operator', dataoperator);
            $(this).parents('.pilot-row:eq(0)').find('input[name=value]').val('').next('label[name="digitsTip"]').remove();
            //if ($(this).parents('.pilot-row:eq(0)').find('.SumoSelect').length > 0) {
            //    $(this).parents('.pilot-row:eq(0)').find('.SumoSelect').remove();
            //}
            console.log('form-group:data-type', $(this).parents('.form-group').attr('data-type'));
            if ($(this).parents('.form-group').attr('data-type') == 'Main') {
                //FilterDialog.bindInput($(this), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, $(this).parents('.pilot-row:eq(0)').attr('data-attributeid'), EntityId, ddlitems, $(this).parents('.pilot-row:eq(0)').attr('data-optionsetid'));
                datatype = datatype == "primarykey" ? 'lookup' : datatype;
                if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                    FilterDialog.bindInput($(this), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, $(this).parents('.pilot-row:eq(0)').attr('data-attributeid'), relevantEntityId, ddlitems, $(this).parents('.pilot-row:eq(0)').attr('data-optionsetid'));
                } else {

                    FilterDialog.bindInput($(this), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, $(this).parents('.pilot-row:eq(0)').attr('data-attributeid'), EntityId, ddlitems, $(this).parents('.pilot-row:eq(0)').attr('data-optionsetid'));
                }
            } else if ($(this).parents('.form-group').attr('data-type') == 'Relevant') {
                FilterDialog.bindInput($(this), $(this).parents('.pilot-row:eq(0)').find('input'), datatype, $(this).parents('.pilot-row:eq(0)').attr('data-attributeid'), RelevantEntityId, ddlitems, $(this).parents('.pilot-row:eq(0)').attr('data-optionsetid'));
            }
            var _value = $(this).find('option:selected').val();
            var _par = $(this).parents('.pilot-row:eq(0)');
            if (datatype == 'datetime') {
                // console.log($(this).find('option:selected').val()*1)
                console.log('_value',_value, _value * 1 != 26)
                if (_value * 1 >= 14 && _value * 1 <= 31 && (_value * 1 != 26 && _value * 1 != 27 && _value * 1 != 28 && _value * 1 != 29) || (_value>77 && _value<=81)) {
                    _par.find('input[name="value"]').prop('disabled', true);
                } else {
                    _par.find('input[name="value"]').prop('disabled', false);
                }
            } else if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                if (_value * 1 >= 41 && _value * 1 <= 44 || (_value * 1 >= 74 && _value * 1 <= 75)) {
                    _par.children('div:last').hide();
                } else {
                    _par.children('div:last').show();
                    //_par.find('input[name="value"],button').prop('disabled', false);
                }
            }
        });
        //收回弹出菜单
        $(document).bind("click", function (e) {
            e = e || window.event;
            var target = e.target || e.srcElement;
            if ($(target).closest(".pilot-choose").length <= 0) {
                downRemove($('.list-group-menu'));
            }
        });
        if (typeof isEditReport == 'undefined' || isEditReport == false) {
            if (typeof EntityId != 'undefined') {
                ScrloadFilterAttributes(EntityId, 'pilot-fieldM', null, null);
            }
            if (typeof RelevantEntityId != 'undefined' && RelevantEntityId != '') {
                $('.form-group[data-type="Relevant"]').show();
                $('.form-group[data-type="Relevant"]').prev().show();
                $('.form-group[data-type="Relevant"]').prev().prev().show();
                ScrloadFilterAttributes(RelevantEntityId, 'pilot-fieldR', null, null);
            }
            else {
                $('.form-group[data-type="Relevant"]').hide();
                $('.form-group[data-type="Relevant"]').prev().hide();
                $('.form-group[data-type="Relevant"]').prev().prev().hide();
            }
        }
    })
    //加载过滤条件字段选项
    function ScrloadFilterAttributes(entityid, classname, that, onsuccess) {
        var _ScrmainOptions = new Array(), _ScrrelatedOptions = new Array();
        Xms.Schema.GetAttributesByEntityId(entityid, function (data) {
            if (!data) return;
            _ScrmainOptions.push('<optgroup data-type="filed" label="字段">');
            console.log('data.content.items', data)
            $(data).each(function (i, n) {
                var otherData = '';
                if (typeof n.optionsetid != 'undefined') {
                    otherData += ' data-optionsetid="' + n.optionsetid + '" ';
                } else {
                    otherData += ' data-optionsetid="null" ';
                }
                _ScrmainOptions.push('<option ' + otherData + ' data-entityid="' + n.entityid + '" data-referencedentityid="' + n.referencedentityid + '" data-attributeid="' + n.attributeid + '" data-referencedentityname="' + n.referencedentityname + '" data-relevant="false" value="' + n.name + '" data-entityname="' + n.entityname + '" data-type="' + n.attributetypename + '">' + n.localizedname + '</option>');
            });
            _ScrmainOptions.push('</optgroup>');
            Xms.Schema.GetEntityRelations(entityid, null,  function (data) {
                if (!data ) {
                    return;
                }
                _ScrrelatedOptions.push('<optgroup data-type="entity" label="关联">');
                console.log('relationship data:data.content', data.content);
                $(data).each(function (ii, nn) {
                    _ScrrelatedOptions.push('<option data-relevant="true" data-name="' + nn.name + '" data-entityid="' + nn.referencedentityid + '" value="' + nn.referencedattributename + '" data-fromattrname="' + nn.referencingattributename + '" data-entityname="' + nn.referencedentityname + '" data-type="' + nn.referencedattributetypename + '">' + nn.referencingattributelocalizedname + '(' + nn.referencedentitylocalizedname + ')' + '</option>');
                });
                _ScrrelatedOptions.push('</optgroup>');
                if (classname != '' && classname != null) {
                    $('#pliot-page1').find('.' + classname).append($(_ScrmainOptions.join('') + _ScrrelatedOptions.join('')));
                }
                else if (that != null) {
                    $(that).append($(_ScrmainOptions.join('') + _ScrrelatedOptions.join('')));
                }
                if (onsuccess != null) {
                    onsuccess(_ScrmainOptions.join('') + _ScrrelatedOptions.join(''));
                }
            });
        });
    }
    //加载编辑筛选条件
    function initFilter(fetchconfig, target) {
        var type = 'Main';
        var attrSel = 'pilot-fieldM';
        var entityid = EntityId;
        if (target.attr('data-type') == 'Relevant') {
            type = 'Relevant';
            attrSel = 'pilot-fieldR';
            entityid = RelevantEntityId;
        } else {
            type = 'Main';
            attrSel = 'pilot-fieldM';
        }
        var filters = fetchconfig.Criteria.Filters;
        var filterHtml = EditFilterHtml(filters, type, entityid, EntityName);
        var condition = fetchconfig.Criteria.Conditions;
        var conditionHtml = EditRowHtml(condition, type, "false", entityid, EntityName);
        var linkEn = fetchconfig.LinkEntities;
        var linkEnHtml = EditRelevantHtml(linkEn, type);
        var NewRow = target.find('.pilot-row:last').clone();
        target.html('');
        target.prepend(linkEnHtml.join(''));
        target.prepend(conditionHtml.join(''));
        target.prepend(filterHtml.join(''));
        ScrloadFilterAttributes(entityid, attrSel, null, function () {
            target.find('.pilot-row:not(.relevant-box)').each(function (i, n) {
                EditRowSet(n, attrSel,false);
            });
            target.find('.relevant-box').each(function (i, n) {
                //变为小写
                $(n).find('option[data-relevant="true"]').each(function (ii, nn) {
                    var opRelation = $(nn).attr('data-name').toLowerCase();
                    $(nn).attr('data-name', opRelation);
                });
                var relRelation = $(n).attr('data-rrelationship').toLowerCase();
                var relEntityid = $(n).attr('data-rentityid');
                var relThat = $(n).children('.relevant-item');
                relThat.children('.' + attrSel).find('option[data-name="' + relRelation + '"]').prop('selected', true);
                ScrloadFilterAttributes(relEntityid, null, null, function (dataHtml) {
                    var selHtml = $(dataHtml);
                    selHtml.find('option[data-relevant="true"]').each(function (ii, nn) {
                        var opRelation = $(nn).attr('data-name').toLowerCase();
                        $(nn).attr('data-name', opRelation);
                    });
                    var ajaxThat = relThat;

                    ajaxThat.children('.relevant-child').children('.pilot-row').children().children('.' + attrSel).html(selHtml);
                    ajaxThat.children('.relevant-child').children('.pilot-row[data-entity="false"]').each(function (ii, nn) {
                        EditRowSet(nn, attrSel,true);
                    });
                    ajaxThat.children('.relevant-child').children('.pilot-row[data-entity="true"]').each(function (ii, nn) {
                        var chilRelation = $(nn).attr('data-rrelationship').toLowerCase();
                        $(nn).attr('data-rrelationship', chilRelation);
                        $(nn).children('.relevant-item').children('.' + attrSel).find('option[data-name="' + chilRelation + '"]').prop('selected', true);
                    });
                });
            })
            target.append(NewRow);
            if (typeof isEditReport != 'undefined' && isEditReport == true) {
                if (target.attr('data-type') != 'Relevant') {
                    if (typeof EntityId != 'undefined') {
                        ScrloadFilterAttributes(EntityId, 'pilot-fieldM', null, null);
                    }
                }
                if (target.attr('data-type') == 'Relevant') {
                    if (typeof RelevantEntityId != 'undefined' && RelevantEntityId != '') {
                        ScrloadFilterAttributes(RelevantEntityId, 'pilot-fieldR', null, null);
                    }
                }
            }
        });

    }
    //恢复行设置
    function EditRowSet(n, attrSel,isRelevant) {
        if ($(n).attr('data-relevant') == 'false' || isRelevant) {
            var attrId = $(n).attr('data-attributeid');
            var attrOperator = $(n).attr('data-operator');
            var attrVal = $(n).attr('data-val');

            $(n).find('.' + attrSel).find('option[data-attributeid="' + attrId + '"]').prop('selected', true);
            $(n).find('.' + attrSel).change();
            $(n).find('.pilot-condition').find('option[value="' + attrOperator + '"]').prop('selected', true);
            $(n).find('.pilot-condition').change();
            var valid = $(n).find('.' + attrSel).find('option[data-attributeid="' + attrId + '"]').attr("data-referencedentityid");

            var datatype = $(n).attr('data-type');
            if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                Xms.Web.GetJson('/api/data/Retrieve/ReferencedRecord/' + valid + '/' + attrVal, null, function (response) {
                    //console.log('response',response)
                    if (response.IsSuccess) {
                        $(n).find('input').val(response.content.name);
                    }
                });
                $(n).find('input').attr("data-value",attrVal);
            } else {
                $(n).find('input').val(attrVal);
            }
            if ($(n).find('input').siblings('select').length > 0) {
                $(n).find('input').siblings('select').find('option[value="' + attrVal + '"]').prop('selected', true);
            }
        }
    }
    //组合筛选条件组html
    function EditFilterHtml(filters, type, entityid, entityname) {
        var _html = [];
        for (var i = 0; i < filters.length; i++) {
            var grounpId = 'group_' + Math.round(new Date().getTime() / 1000);
            var groupType = 'and';
            var groupTypeCh = '和';
            if (filters[i].FilterOperator == 1) {//或者
                groupType = 'or';
                groupTypeCh = '或';
            } else if (filters[i].FilterOperator == 0) {//并且
                groupType = 'and';
                groupTypeCh = '和';
            }
            _html.push('<div class="andorGroup row" id="' + grounpId + '" data-type="' + groupType + '" >');
            _html.push('<div class="col-sm-1">');
            _html.push('<span>' + groupTypeCh + '</span>');
            _html.push('<em class="pilot-choose" onclick="downSelect(this,\'group\')" style="background: url(/content/imgs/selectListR.png) center no-repeat;position:absolute;height: 15px;width: 15px;top: 30%;left: 50%;cursor: pointer;">');
            _html.push('</em>');
            _html.push('</div>');
            _html.push('<div class="col-sm-11">');
            var chilFilter = EditFilterHtml(filters[i].Filters, type, entityid, entityname);
            if (chilFilter.length > 0) {
                _html.push(chilFilter.join(''));
            }
            var chilRow = EditRowHtml(filters[i].Conditions, type, "false", entityid, entityname);
            if (chilRow.length > 0) {
                _html.push(chilRow.join(''));
            }
            _html.push('</div>');
            _html.push('</div>');
        }
        return _html;
    }
    //组合筛选条件行html
    function EditRowHtml(conditions, type, isrelevant, entityid, entityname) {
        var _html = [];
        for (var i = 0; i < conditions.length; i++) {
            var rowId = 'row_' + Math.round(Math.random()*10000000).toString(16);
            var attrName = conditions[i].AttributeName;
            var values = conditions[i].Values;
            var operator = conditions[i].Operator;
            Xms.Web.AsyncGet('/api/schema/attribute/getbyentityid/' + entityid + '/' + attrName, function (data) {
                console.log(i, entityid, attrName)
                var result = JSON.parse(data.Content);
                if (result != null) {

                    var attrType = result.attributetypename;
                    var attrId = result.attributeid;
                    var attrOptionsetId = 'null';
                    if (result.optionsetid != null) {
                        attrOptionsetId = result.optionsetid;
                    }
                    _html.push('<div id="' + rowId + '" class="pilot-row row" data-isshow="show" style="margin-bottom: 5px;" data-entity="false" data-relevant="' + isrelevant + '" data-attributename="' + attrName + '" data-entityname="' + entityname + '" data-attributeid="' + attrId + '" data-optionsetid="' + attrOptionsetId + '" data-operator="' + operator + '" data-val="' + values + '">');
                    _html.push('<div class="col-sm-1" style="position:relative;height:30px;">');
                    _html.push('<em class="pilot-choose" onclick="downSelect(this,\'row\')" style="position: absolute; height: 15px; width: 15px; top: 30%; left: 50%; cursor: pointer; background: url(/content/imgs/selectListR.png) 50% 50% no-repeat;">');
                    _html.push('</em>');
                    _html.push('</div>');
                    _html.push('<div class="col-sm-4">');
                    if (type == 'Relevant') {
                        _html.push('<select class="form-control pilot-fieldR input-sm">');
                    } else {
                        _html.push('<select class="form-control pilot-fieldM input-sm">');
                    }
                    _html.push('</select>');
                    _html.push('</div>');
                    _html.push('<div class="col-sm-3">');
                    _html.push('<select class="form-control pilot-condition input-sm">');
                    _html.push('</select>');
                    _html.push('</div>');
                    _html.push('<div class="col-sm-4">');
                    _html.push('<input class="form-control input-sm" name="value" type="text" value="" />')
                    _html.push('</div>');
                    _html.push('<br />');
                    _html.push('</div>');
                }
            });
        }
        return _html;
    }
    function EditRelevantHtml(linkEntity, type) {
        var _html = [];
        for (var i = 0; i < linkEntity.length; i++) {
            var rowId = 'row_' + Math.round(Math.random() * 10000000).toString(16);
            var rentityname = linkEntity[i].LinkToEntityName;
            var rrelationship = linkEntity[i].EntityAlias;
            Xms.Web.AsyncGet('/api/schema/entity/getbyname/' + rentityname, function (data) {
                if (typeof linkEntity[i].LinkCriteria != 'undefined' && linkEntity[i].LinkCriteria && linkEntity[i].LinkCriteria.Conditions.length > 0) {
                    var critTarget = linkEntity[i].LinkCriteria;
                    var result = JSON.parse(data.Content);
                    var entityid = result.entityid;
                    var entityname = rentityname;
                    _html.push('<div id="' + rowId + '" class="pilot-row row relevant-box" data-isshow="show" style="margin-bottom:5px;" data-entity="true" data-relevant="true" data-rentityid="' + entityid + '" data-rentityname="' + rentityname + '" data-rrelationship="' + rrelationship + '">');
                    _html.push('<div class="col-sm-1" style="position:relative;height:30px;">');
                    _html.push('<em class="pilot-choose" onclick="downSelect(this,\'row\')" style="position: absolute; height: 15px; width: 15px; top: 30%; left: 50%; cursor: pointer; background: url(/content/imgs/selectListR.png) 50% 50% no-repeat;">');
                    _html.push('</em>');
                    _html.push('</div>');
                    _html.push('<div class="col-sm-11 relevant-item" data-name="' + rrelationship + '">');
                    if (type == 'Relevant') {
                        _html.push('<select class="form-control pilot-fieldR input-sm">');
                    } else {
                        _html.push('<select class="form-control pilot-fieldM input-sm">');
                    }
                    _html.push('</select>');
                    _html.push('<div class="relevant-child">');
                    var filters = critTarget.Filters;
                    var filterHtml = EditFilterHtml(filters, type, entityid, entityname);
                    _html.push(filterHtml.join(''));
                    var condition = critTarget.Conditions;
                    var conditionHtml = EditRowHtml(condition, type, "ture", entityid, entityname);
                    _html.push(conditionHtml.join(''));
                    if (linkEntity[i].LinkCriteria && linkEntity[i].LinkCriteria.Conditions.length > 0) {
                        var linkTarget = linkEntity[i].LinkEntities;
                        _html.push(EditRelevantHtml(linkTarget, type).join(''));
                    }
                    _html.push('</div>');
                    _html.push('</div>');
                    _html.push('</div>');
                }
            });
        }
        return _html;
    }

    //复制新行
    function CopyNewRow(that, isentity, isrelevant, entityid) {
        var newSelect = that.clone();
        newSelect.prop('id','row_' + Math.round(Math.random()*10000000).toString(16));
        if (entityid == '') {
            newSelect.find('option[value=""]').prop('selected', true);
        } else {
            newSelect.find('select').html('');
            newSelect.find('select').append('<option value="">--请选择--</option>');
            ScrloadFilterAttributes(entityid, '', newSelect.find('select:eq(0)'), null);
        }
        newSelect.attr('data-entity', isentity);
        newSelect.attr('data-relevant', isrelevant);
        return newSelect;
    }
    //第一页选择关联实体方法
    function relevantEvent(that, dataentityname) {
        var Rentityid = that.find('option:selected').attr('data-entityid');
        var Rrelationship = that.find('option:selected').attr('data-name');
        that.parents('.pilot-row:eq(0)').attr('data-entity', 'true');
        that.parents('.pilot-row:eq(0)').attr('data-relevant', 'true');
        that.parents('.pilot-row:eq(0)').attr('data-rentityid', Rentityid);
        that.parents('.pilot-row:eq(0)').attr('data-rentityname', dataentityname);
        that.parents('.pilot-row:eq(0)').attr('data-rrelationship', Rrelationship);
        that.parents('.pilot-row:eq(0)').addClass('relevant-box');
        that.parent().removeClass().addClass('col-sm-11').addClass('relevant-item').attr('data-name', Rrelationship);
        that.parent().nextAll().remove();
        var newSelect = CopyNewRow(that.parents('.form-group').find('.pilot-row:last'), 'false', 'true', Rentityid);
        if (that.siblings('.relevant-child').length <= 0) {
            newSelect = $('<div class="relevant-child"></div>').append(newSelect);
            that.after(newSelect);
        } else {
            that.siblings('.relevant-child').append(newSelect);
        }
        if (that.parents('.pilot-row:eq(0)').parents('.pilot-row').length > 0) {
            var newSelect2 = CopyNewRow(that.parents('.form-group').find('.pilot-row:last'), 'false', 'true', that.parents('.pilot-row:eq(1)').attr('data-rentityid'));
            that.parents('.pilot-row:eq(0)').before(newSelect2);
        }
        that.find('optgroup[data-type="filed"]').remove();
        that.find('option[value=""]').remove();
    }
    function clearRowGroup(e) {
        if (typeof e != 'undefined') {
            $(e).parents('.form-group').next('.form-group').find('.pilot-row , .andorGroup').not('.pilot-row:last').remove();
        } else {
            $('.form-group[data-type="Main"],.form-group[data-type="Relevant"]').next('.form-group').find('.pilot-row , .andorGroup').not('.pilot-row:last').remove();
        }
    }

    function chooseRowGroup(e, rowId) {
        var that = $('#' + rowId);
        that.css('background', '#d9edf7');
        that.addClass('active');
        downRemove($(e).parents('.list-group'));
    }
    function canelchooseRowGroup(e, rowId) {
        var that = $('#' + rowId);
        that.css('background', '');
        that.removeClass('active');
        downRemove($(e).parents('.list-group'));
    }
    function rowShow(e, rowId) {
        var that = $('#' + rowId);
        that.attr('data-isShow', 'show');
        downRemove($(e).parents('.list-group'));
    }
    function rowHide(e, rowId) {
        var that = $('#' + rowId);
        that.attr('data-isShow', 'hide');
        downRemove($(e).parents('.list-group'));
    }
    function rowRemove(e, rowId) {
        var that = $('#' + rowId);
        that.remove();
        downRemove($(e).parents('.list-group'));
    }
    function downRemove(e) {
        $(e).remove();
    }
    function groupAndOr(e, type) {
        var acList = $(e).parents('.form-group').next().children('.active:not(.andorGroup)');
        var relaveAcList = $(e).parents('.form-group').next().find('.active[data-relevant=true]');
        var groupAcList = $(e).parents('.form-group').next().children('.andorGroup.active');
        if ((acList.length > 0 && relaveAcList.length > 0) || (acList.length > 0 && groupAcList.length > 0) || (relaveAcList.length > 0 && groupAcList.length > 0)) {
            Xms.Web.Alert(false, '不能跨级合并')
            return false;
        }
        var targetList = acList.length > 0 ? acList : 0;
        targetList = relaveAcList.length > 0 ? relaveAcList : targetList;
        targetList = groupAcList.length > 0 ? groupAcList : targetList;
        if (targetList.length <= 1) {
            downRemove($(e).parents('.list-group'));
            if ($(e).parents('.form-group').children('span').length == 0) {
                $(e).parents('.form-group').append('<span>选择两条数据才能组合</span>')
            }
            return false;
        }
        else {
            $(e).parents('.form-group').children('span').remove();
        }
        var targetPar = $(targetList[0]).parent();
        var grounpId = 'group_' + Math.round(new Date().getTime() / 1000);
        var divHtml = [];
        divHtml.push('<div class="andorGroup row" id="' + grounpId + '" data-type="' + type + '">');
        divHtml.push('<div class="col-sm-1">');
        if (type == 'and') {
            divHtml.push('<span>和</span>');
        } else {
            divHtml.push('<span>或</span>');
        }
        divHtml.push('<em class="pilot-choose" onclick="downSelect(this,\'group\')" style="background: url(/content/imgs/selectListR.png) center no-repeat;position:absolute;height: 15px;width: 15px;top: 30%;left: 50%;cursor: pointer;"></em></div>');
        divHtml.push('<div class="col-sm-11"></div>');
        divHtml.push('</div>');
        var groupHtml = $(divHtml.join(''));
        targetList.each(function (i, n) {
            $(n).css('background', '');
            $(n).removeClass('active');
            groupHtml.children('.col-sm-11').append($(n).clone());
            $(n).remove();
        });
        targetPar.prepend(groupHtml);
    }
    function changeAnd(e, rowId) {
        var that = $('#' + rowId);
        that.find('span').text('和');
        that.attr('data-type', 'and');
        downRemove($(e).parents('.list-group'));
    }
    function changeOr(e, rowId) {
        var that = $('#' + rowId);
        that.find('span').text('或');
        that.attr('data-type', 'or');
        downRemove($(e).parents('.list-group'));
    }
    function addSon(e, rowId) {
        var that = $('#' + rowId);
        var rowCopy = that.parents('.form-group').find('.pilot-row:last').clone();
        rowCopy.prop('id', 'row_' + Math.round(Math.random()*10000000).toString(16));
        that.children('.col-sm-11').append(rowCopy);
        downRemove($(e).parents('.list-group'));
    }
    function canelGroup(e, rowId) {
        var that = $('#' + rowId);
        that.find('.pilot-row').each(function (i, n) {
            that.after($(n).clone());
        });
        that.remove();
        downRemove($(e).parents('.list-group'));
    }
    function downSelect(e, type) {
        downRemove($('.list-group-menu'));
        if (type == 'row') {
            var rowId = $(e).parents('.pilot-row:eq(0)').prop('id');
        } else {
            var rowId = $(e).parents('.andorGroup').prop('id');
        }
        var choose = '<a href="javascript:void(0);" onclick="chooseRowGroup(this,\'' + rowId + '\')" data-event="">选择行</a>';
        var canelchoose = '<a href="javascript:void(0);" onclick="canelchooseRowGroup(this,\'' + rowId + '\')" data-event="">取消选择行</a>';
        //var show = '<a href="javascript:void(0);" onclick="rowShow(this,\'' + rowId + '\')" data-event="">在简单模式中显示</a>';
        //var hide = '<a href="javascript:void(0);" onclick="rowHide(this,\'' + rowId + '\')" data-event="">在简单模式中隐藏</a>';
        var del = '<a href="javascript:void(0);" onclick="rowRemove(this,\'' + rowId + '\')" data-event="">删除</a>';
        var choosegroup = '<a href="javascript:void(0);" onclick="chooseRowGroup(this,\'' + rowId + '\')" data-event="">选择组</a>';
        var canelchoosegroup = '<a href="javascript:void(0);" onclick="canelchooseRowGroup(this,\'' + rowId + '\')" data-event="">取消选择组</a>';
        var canelgroup = '<a href="javascript:void(0);" onclick="canelGroup(this,\'' + rowId + '\')" data-event="">取消组合</a>';
        var changeand = '<a href="javascript:void(0);" onclick="changeAnd(this,\'' + rowId + '\')" data-event="">更改为 和</a>';
        var changeor = '<a href="javascript:void(0);" onclick="changeOr(this,\'' + rowId + '\')" data-event="">更改为 或</a>';
        var addson = '<a href="javascript:void(0);" onclick="addSon(this,\'' + rowId + '\')" data-event="">添加子句</a>';
        var _html = [];
        _html.push('<div>');
        if (type == 'row') {
            _html.push(choose);
            _html.push(canelchoose);
            //_html.push(show);
            //_html.push(hide);
            _html.push(del);
        }
        else {
            _html.push(choosegroup);
            _html.push(canelchoosegroup);
            _html.push(canelgroup);
            _html.push(changeand);
            _html.push(changeor);
            _html.push(addson);
            _html.push(del);
        }
        _html.push('</div>');
        var eTop = $(e).offset().top;
        var eLeft = $(e).offset().left;
        var ulhtml = $(_html.join(''));
        ulhtml.css({ 'position': 'fixed', 'top': eTop, 'left': eLeft, 'background': '#fff', 'z-index': 10000 }).addClass('list-group').addClass('list-group-menu');
        ulhtml.find('a').addClass('list-group-item');
        $('body').append(ulhtml);
    }

    function getDdlItems(datatype) {
        var items = [];
        if (datatype == 'picklist') {
            items = [{ value: 0, text: '' }];
        } else if (datatype == 'state') {
            items = [{ value: 0, text: '否' }, { value: 1, text: '是' }];
        } else if (datatype == 'bit') {
            items = [{ value: 0, text: '否' }, { value: 1, text: '是' }];
        }
        return items;
    }

    function eachGroup(e, isFirst) {
        var FiltersConfig = new Xms.Fetch.FilterExpression(Xms.Fetch.LogicalOperator.And);
        console.log('filtersconfig',FiltersConfig);
        $(e).each(function (i, n) {
            if ($(n).hasClass('andorGroup')) {
                var FiltersConfigGroup = new Xms.Fetch.FilterExpression(Xms.Fetch.LogicalOperator.And);
                $(n).children().children('.pilot-row').each(function (ii, nn) {
                    if ($(nn).find('.pilot-fieldM,.pilot-fieldR').find('option:selected').val() != '') {
                        var vale = $(nn).find('input[name="value"]').val();
                        var datatye = $(nn).find('.pilot-fieldM,.pilot-fieldR').find('option:selected').attr("data-type");

                        if (datatye == "lookup" || datatye == "owner" || datatye == "customer" || datatye == 'primarykey') {
                            vale = $(nn).find('input[name="value"]').attr("data-value");
                            vale = [vale];
                        } else if (datatye == "picklist") {
                            vale = vale.split(',');
                        } else {
                            vale = [vale];
                        }
                        var item = {
                            AttributeName: $(nn).attr('data-attributename').toLowerCase(),
                            Operator: $(nn).attr('data-operator'),
                            Values: vale
                        };
                        FiltersConfigGroup.Conditions.push(item);
                    }
                });
                if ($(n).attr('data-type') == 'and') {
                    FiltersConfigGroup.FilterOperator = Xms.Fetch.LogicalOperator.And;
                }
                else {
                    FiltersConfigGroup.FilterOperator = Xms.Fetch.LogicalOperator.Or;
                }
                $(n).children().children('.andorGroup').each(function (ii, nn) {
                    FiltersConfigGroup.Filters.push(eachGroup(nn, false));
                });
                if (isFirst) {
                    FiltersConfig.Filters.push(FiltersConfigGroup);
                } else {
                    FiltersConfig = FiltersConfigGroup;
                }
            }
            else {
                if ($(n).find('.pilot-fieldM,.pilot-fieldR').find('option:selected').val() != '') {
                    //FiltersConfig = new Xms.Fetch.FilterExpression();
                    var vale = $(n).find('input[name="value"]').val();
                    var datatye = $(n).find('.pilot-fieldM,.pilot-fieldR').find('option:selected').attr("data-type");

                    if (datatye == "lookup" || datatye == "owner" || datatye == "customer" || datatye == 'primarykey') {
                        vale = $(n).find('input[name="value"]').attr("data-value");
                        if (!vale && $(n).find('input[name="value"]').val() != "") {
                            vale = $(n).find('input[name="value"]').val();
                        } else {
                            vale = [vale];
                        }
                    } else if (datatye == "picklist") {
                        vale = vale.split(',');
                    } else {
                        vale = [vale];
                    }
                    var item = {
                        AttributeName: $(n).attr('data-attributename').toLowerCase(),
                        Operator: $(n).attr('data-operator'),
                        Values: vale
                    };
                    FiltersConfig.Conditions.push(item);
                }
            }
        });
        return FiltersConfig
    }
    function eachRelevant(e, entityrelationship) {
        var rItem = [];
        console.log('entityrelationship', entityrelationship);
        $(e).each(function (i, n) {
            var relevantItem = new LinkEntity();
            var filterList = $(n).children().children('.relevant-child').children('.andorGroup,.pilot-row[data-entity="false"]');
            relevantItem.LinkCriteria = new Xms.Fetch.FilterExpression(Xms.Fetch.LogicalOperator.And);
            relevantItem.LinkCriteria = eachGroup(filterList, true);

            var rrelationship = $(n).attr('data-rrelationship');
            var rentityname = $(n).attr('data-rentityname');
            var fromattrname = $(n).find('.pilot-fieldM:first option:selected').attr('data-fromattrname');
            console.log('rentityname', fromattrname)
            relevantItem.LinkToEntityName = rentityname;
            relevantItem.EntityAlias = rrelationship;
            relevantItem.LinkToAttributeName = rentityname + 'id';
            relevantItem.LinkFromEntityName = entityrelationship;
            relevantItem.LinkFromAttributeName = fromattrname;
            relevantItem.LinkEntities = [];
            $(n).children('.relevant-item').children('.relevant-child').children('.relevant-box').each(function (ii, nn) {
                relevantItem.LinkEntities = eachRelevant($(nn), entityrelationship, false);
            });
            console.log('relevantItem', relevantItem)
            rItem.push(relevantItem);
        });
        return rItem;
    }
</script>